package com.gxuwz.stats.controller.twoAdmin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.entity.AcademicWork;
import com.gxuwz.stats.entity.DecisionConsulting;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.DecisionConsultingService;
import com.gxuwz.stats.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/twoDeConsult")
public class DecisionConsultTwoController {
    @Autowired
    private DecisionConsultingService decisionConsultingService;
    @Autowired
    private UserService userService;

    /**
     * 分页查询
     * @param params
     * @param currentPage
     * @param pageSize
     * @return
     */
    @GetMapping("/consultingList")
    public ResponseEntity<Map<String, Object>> getConsultingList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestHeader("Authorization") String authorization) {
        try {
            // 提取 Token 并解析用户信息
            String token = authorization.replace("Bearer ", "");
            JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
            String department = jwtTokenUtil.getDepartmentFromToken(token); // 获取部门信息

            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<DecisionConsulting> page = new Page<>(currentPage, pageSize);
            QueryWrapper<DecisionConsulting> queryWrapper = new QueryWrapper<>();

// 二级学院管理员，添加 department 过滤条件
            if (department != null && !department.isEmpty()) {
                queryWrapper.eq("u.department", department); // 只查询当前部门的数据
            }

            if (params.containsKey("username") && !params.get("username").isEmpty()) {
                queryWrapper.like("username", params.get("username"));
            }

            // 模糊查询条件 - 成果名称
            if (params.containsKey("consultingResultName") && params.get("consultingResultName") != null && !params.get("consultingResultName").isEmpty()) {
                queryWrapper.like("consulting_result_name", params.get("consultingResultName"));
            }

            // 模糊查询条件 - 成果类别
            if (params.containsKey("consultingCategory") && params.get("consultingCategory") != null && !params.get("consultingCategory").isEmpty()) {
                queryWrapper.like("consulting_category", params.get("consultingCategory"));
            }

            // 调用 service 层的分页查询方法
            IPage<DecisionConsulting> resultPage = decisionConsultingService.getToAdminDecisionConsultingList(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords());
            response.put("total", resultPage.getTotal());
            response.put("currentPage", resultPage.getCurrent());
            response.put("pageSize", resultPage.getSize());
            response.put("totalPages", resultPage.getPages());

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增决策咨询数据
     */
    @PostMapping("/addTwoAdminConsulting")
    public ResponseEntity<Map<String, Object>> saveConsulting(@RequestBody DecisionConsulting decisionConsulting) {
        System.out.println("前端数据：" + decisionConsulting);

        // 创建响应 Map
        Map<String, Object> response = new HashMap<>();
         //1. 验证 username 是否存在
        String username = decisionConsulting.getUsername();
        if (username == null || username.isEmpty()) {
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 根据 username 查询 user_id
        String userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
//        System.out.println("获取到的 user_id：" + userId);

        // 3. 设置 user_id 并保存
        decisionConsulting.setUserId(userId);

        int baseScore = decisionConsultingService.getScoreByType(decisionConsulting.getConsultingCategory());
        decisionConsulting.setConsultingScore(baseScore);
        // 2. 计算总分值并保存
//        decisionConsultingService.calculateTotalScore(decisionConsulting);

        try {
            // 保存到数据库
            decisionConsultingService.save(decisionConsulting);

            // 返回成功响应
            response.put("code", 200);
            response.put("msg", "新增成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 修改决策咨询数据
     */
    @PutMapping("/updateTwoAdminConsulting")
    public ResponseEntity<Map<String, Object>> updateConsulting(
            @RequestBody DecisionConsulting decisionConsulting
//            @RequestHeader("Authorization") String authorization
    ) {
        // 1. 获取前端传递的用户名
        String username = decisionConsulting.getUsername();
//        System.out.println("shdjs="+username);
        if (username != null && !username.isEmpty()) {
            // 2. 查询用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            System.out.println("user="+user);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("msg", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            // 3. 设置 userId
            decisionConsulting.setUserId(user.getUserId());
        }
        int baseScore = decisionConsultingService.getScoreByType(decisionConsulting.getConsultingCategory());
        decisionConsulting.setConsultingScore(baseScore);
        // 2. 计算总分值并保存
//        decisionConsultingService.calculateTotalScore(decisionConsulting);

        decisionConsultingService.updateById(decisionConsulting);
        Map<String, Object> response = new HashMap<>();
              response.put("code", 200);
              response.put("msg", "修改成功");
              return ResponseEntity.ok(response);
    }

    /**
     * 批量删除决策咨询数据
     */
    @DeleteMapping("/deleteTwoAdminConsulting")
    public ResponseEntity<Map<String, Object>> deleteConsulting(@RequestBody List<Long> ids) {
        decisionConsultingService.removeByIds(ids);
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

}
